package com.lsh.timer;

import com.lsh.entity.Monitor;
import com.lsh.entity.Response;
import com.lsh.repository.MonitorRepository;
import com.lsh.service.Impl.WXServiceImpl;
import com.lsh.util.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/10/18 4:09 下午
 * @desc ：
 */
@Slf4j
@Component
@EnableAsync
public class SurviveTask {
//    public static Boolean isRun= false;
    @Autowired
    MonitorRepository repository;
    @Autowired
    WXServiceImpl wxService;

    @Async
    @Scheduled(cron = "0 */1 * * * ?")
    public void survive(){
        log.info("- 存活监控定时任务执行了");
//        if(isRun == true){
//            return;
//        }
//        isRun = true;
        String datetime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        List<Monitor> monitorList = repository.findByStart_timeAfter8AndEnd_timeBefore24AndFlagIsNot1();
        if (monitorList.size() == 0 || monitorList == null){
            return;
        }
        String name = null;
        String url = null;
        for (Monitor monitor : monitorList) {
            log.info(monitor.toString());
             name = monitor.getName();
             url = monitor.getUrl();
            Response response = HttpClient.doGet(url);
            log.info("- response："+response);
            if (response == null || !"200".equals(response.getCode())){
                log.error("- "+name+","+url+","+datetime+"服务宕机");
                wxService.sendWXMessage(name+" 平台 "+url+" ",datetime);
                log.error("- "+name+","+url+" 已下发微信通知");
            }else {
                log.info("- "+name+"在"+datetime+"时间状态正常");
            }
        }
//        isRun = false;
    }
}
